// auth/auth-manager.js
import ssoStrategies from '../utils/ssoStrategies.js';
export class AuthManager {
  constructor(jsBridge, config) {
    this.jsBridge = jsBridge
    this.config = config
    console.log("🚀 ~ auth-manager.js:6 ~ AuthManager ~ constructor ~ this.config:", this.config)
    this.token = null
    this.userInfo = null
    this.login()
  }
 async getTicket(){
    // 获取公司的名称
   const getcompanyName = this.config.get('content.auth.companyName', 'compayA')
   console.log(12345,ssoStrategies);

    //通过js文件将ticket方法获取
     if (!ssoStrategies[getcompanyName]) {
      throw new Error(`未找到公司[${getcompanyName}]的SSO策略`);
    }
    this.strategy = ssoStrategies[getcompanyName];
  try {
      const result = await this.strategy.getTicket();
      console.log("🚀 ~ auth-manager.js:24 ~ AuthManager ~ getTicket ~ result:", result)
      return result;
    } catch (error) {
      console.error(`[${this.strategy.name}] 获取ticket失败:`, error);
      throw error;
    }

  }
  async login() {
    const loginConfig = this.config.get('content.auth.loginMethod', 'native')
    console.log("🚀 ~ auth-manager.js:13 ~ AuthManager ~ login ~ loginConfig:", loginConfig)

    switch (loginConfig) {
      case 'sso':
        return await this.ssoLogin()
      case 'oauth':
        return await this.oauthLogin()
      case 'native':
      default:
        return await this.nativeLogin()
    }
  }

  async ssoLogin() {//登录逻辑
    const ssoConfig = this.config.get('content.auth.sso')
    console.log("🚀 ~ auth-manager.js:26 ~ AuthManager ~ ssoLogin ~ ssoConfig:", ssoConfig)

    // // SSO登录逻辑
    // const token = await this.jsBridge.invoke('getSSOToken')

    // if (token) {
    //   this.token = token
    //   await this.validateToken(token)
    // } else {
    //   throw new Error('SSO登录失败')
    // }
  }

  async nativeLogin() {
    // 原生登录逻辑
    const result = await this.jsBridge.invoke('showLogin')
    if (result.success) {
      this.token = result.token
      this.userInfo = result.userInfo
    }
    return result
  }

  async validateToken(token) {
    // 验证token有效性
    const isValid = await this.jsBridge.invoke('validateToken', { token })
    if (!isValid) {
      throw new Error('Token验证失败')
    }
  }
}